//
//  KAMonthViewController.m
//  KeepAccounts
//
//  Created by honeyrr on 2017/10/24.
//  Copyright © 2017年 honeyrr. All rights reserved.
//

#import "KAMonthViewController.h"
#import "KAMonthTableViewCell.h"
#import "KAPieChartView.h"
#import "KAMonthTableHeaderView.h"

@interface KAMonthViewController ()<UITableViewDelegate, UITableViewDataSource,KAPieChartViewDelegate>

@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) KAPieChartView *pieChartView;

@property(nonatomic, strong) UILabel *datelabel;
@property(nonatomic, assign) NSInteger year;
@property(nonatomic, assign) NSInteger month;

@property(nonatomic, assign) NSInteger allIncome;
@property(nonatomic, assign) NSInteger allOutlay;

@property(nonatomic, strong) NSArray *currentMonthArr;
@property(nonatomic, strong) NSArray *tableArr;
@property(nonatomic, strong) NSArray *pieChartArr;

@property(nonatomic, assign) BOOL isOutlay;


@end

static NSString *const ID = @"cellID";

@implementation KAMonthViewController

-(NSArray *)currentMonthArr
{
    if (!_currentMonthArr) {
        _currentMonthArr = [NSArray array];
    }
    return _currentMonthArr;
}
-(NSArray *)tableArr
{
    if (!_tableArr) {
        _tableArr = [NSArray array];
    }
    return _tableArr;
}
-(NSArray *)pieChartArr
{
    if (!_pieChartArr) {
        _pieChartArr = [NSArray array];
    }
    return _pieChartArr;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tableArr = [self loadTableViewData:self.datelabel.text];
    self.isOutlay = false;
    [self.tableView reloadData];
    [self reloadPieChartViewData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}


-(void) setupUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    NSDateFormatter *date = [[NSDateFormatter alloc] init];
    date.dateFormat = @"yyyy-MM";
    NSString *today = [date stringFromDate:[NSDate date]];
   
    NSArray *dateArr = [today componentsSeparatedByString:@"-"];
    
    self.year = [dateArr[0] intValue];
    self.month = [dateArr[1] intValue];
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIView *dateView = [UIView new];
    dateView.frame = CGRectMake(0, 0, KAScreenW, 44);
    dateView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:dateView];
    [self setHeaderDateView:dateView];
    
    self.tableArr = [self loadTableViewData:self.datelabel.text];
    [self loadPieChartViewData];
    
    self.pieChartView = [[KAPieChartView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(dateView.frame), KAScreenW, KAScreenW * 0.66)];
    self.pieChartView.pieMarr = self.pieChartArr;
    self.pieChartView.allIncomeMoney = self.allIncome;
    self.pieChartView.allOutlayMoney = self.allOutlay;
    self.pieChartView.delegate = self;
    [self.view addSubview:self.pieChartView];
    
    [self.view addSubview:self.tableView];
    [self.tableView reloadData];
}

-(void) reloadPieChartViewData
{
    [self loadPieChartViewData];
    self.pieChartView.isOutlay = false;
    self.pieChartView.pieMarr = self.pieChartArr;
    self.pieChartView.allIncomeMoney = self.allIncome;
    self.pieChartView.allOutlayMoney = self.allOutlay;
}

-(void)onCenterClick:(KAPieChartView *)pieChartView
{
    self.isOutlay = !self.isOutlay;
    [self.tableView reloadData];
}

-(void) loadAllIncomeAndOutlay
{
    _allIncome = 0;
    _allOutlay = 0;
    for (int i=0; i<self.currentMonthArr.count; i++) {
        if (i == 0) {
            for (KADataBaseModel *model in self.currentMonthArr[i]) {
                _allIncome += [model.money integerValue];
            }
        } else {
            for (KADataBaseModel *model in self.currentMonthArr[i]) {
                _allOutlay += [model.money integerValue];
            }
        }
    }
    NSLog(@"%ld:%ld",_allIncome,_allOutlay);
}

-(void) loadPieChartViewData
{
    NSArray *arr1 = [NSArray array];
    NSArray *arr2 = [NSArray array];
    
    for (int i=0; i<self.tableArr.count; i++) {
        NSMutableArray *marr1 = [NSMutableArray array];
        NSMutableArray *marr2 = [NSMutableArray array];
        NSMutableArray *marr3 = [NSMutableArray array];
        if (i == 0) {
            for (NSDictionary *dict in self.tableArr[i]) {
                [marr1 addObject:dict[@"date"]];
                [marr2 addObject:dict[@"percent"]];
                [marr3 addObject:dict[@"color"]];
            }
            arr1 = @[marr1,marr2,marr3];
        } else {
            for (NSDictionary *dict in self.tableArr[i]) {
                [marr1 addObject:dict[@"date"]];
                [marr2 addObject:dict[@"percent"]];
                [marr3 addObject:dict[@"color"]];
            }
            arr2 = @[marr1,marr2,marr3];
        }
    }
    self.pieChartArr = @[arr1,arr2];
    NSLog(@"pie:%@",self.pieChartArr);
}

-(NSArray *) loadTableViewData:(NSString *)date
{
    NSMutableArray *marr = [NSMutableArray array];
    self.currentMonthArr = [[KAQueryDataBaseModel instance] queryCurrentMonthData:date];
    [self loadAllIncomeAndOutlay];
    NSMutableArray *marr1 = [NSMutableArray array];
    NSArray *marrIncome = [self mergeSameDate:self.currentMonthArr[0]];
    for (int i = 0; i < marrIncome.count; i++) {
        NSMutableDictionary *dict = marrIncome[i];
        float money = [dict[@"money"] floatValue];
        double temp = money / self.allIncome;
        NSString *percent = [NSString stringWithFormat:@"%.01f%%", temp * 100];
        [dict setObject:percent forKey:@"percent"];
        [dict setObject:KAMonthColor[i] forKey:@"color"];
        [marr1 addObject:dict];
    }
    NSMutableArray *marr2 = [NSMutableArray array];
    NSArray *marrOutlay = [self mergeSameDate:self.currentMonthArr[1]];
    for (int i = 0; i < marrOutlay.count; i++) {
        NSMutableDictionary *dict = marrOutlay[i];
        float money = [dict[@"money"] floatValue];
        double temp = money / self.allOutlay;
        NSString *percent = [NSString stringWithFormat:@"%.01f%%", temp * 100];
        [dict setObject:percent forKey:@"percent"];
        [dict setObject:KAMonthColor[i] forKey:@"color"];
        [marr2 addObject:dict];
    }
    [marr addObject:marr1];
    [marr addObject:marr2];
    return marr;
}

-(NSMutableArray *)mergeSameDate:(NSMutableArray *)arr
{
    NSMutableArray *dateArray = [NSMutableArray array];
    for (int i = 0; i < arr.count; i ++) {
        KADataBaseModel *m1 =arr[i];
        NSLog(@"m1:%@",m1);
        NSMutableArray *tempArray = [NSMutableArray new];
        for (int j = 0; j < arr.count; j ++) {
            KADataBaseModel *m2 =arr[j];
            if([m1.date isEqualToString:m2.date]){
                [tempArray addObject:m2];
            }
        }
        //如果tempArray.count > 1 将他添加至数组
        if ([tempArray count] > 1) {
            [dateArray addObject:tempArray];
        }
        //移除出现相同次数的元素
        for (int i = 0; i < [tempArray count] - 1; i++) {
            KADataBaseModel *model1 = tempArray[i];
            for (int j=0; j<arr.count; j++) {
                KADataBaseModel *model2 = arr[j];
                if ([model1.date isEqualToString:model2.date]) {
                    [arr removeObject:arr[j]];
                }
            }
        }
    }
    for (KADataBaseModel *model in arr) {
        BOOL isSame = false;
        for (int i=0; i<dateArray.count; i++) {
            KADataBaseModel *m =dateArray[i][0];
            NSString *date = m.date;
            if ([model.date isEqualToString:date]) {
                isSame = true;
            }
        }
        if (!isSame) {
            [dateArray addObject:@[model]];
        }
    }
    
    NSMutableArray *resultArr = [NSMutableArray array];
    for (NSArray *arr in dateArray) {
        int sum = 0;
        for (int i=0; i<arr.count; i++) {
            sum += [[arr[i] money] intValue];
        }
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:[arr[0] date] forKey:@"date"];
        [dict setObject:[NSString stringWithFormat:@"%d",sum] forKey:@"money"];
        NSLog(@"sum:%d",sum);
        [resultArr addObject:dict];
    }
    return resultArr;
}

-(void)setHeaderDateView:(UIView *)view
{
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(50, 7, 30, 30)];
    [leftBtn setImage:[UIImage imageNamed:@"icon_prev"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftClick) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:leftBtn];
    
    CGFloat Y = 7;
    CGFloat W = 100;
    CGFloat H = 30;
    CGFloat X = view.frame.size.width/2 - W/2;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(X, Y, W, H)];
    label.text = [NSString stringWithFormat:@"%ld-%02ld",self.year,self.month];
    label.textAlignment = NSTextAlignmentCenter;
    [view addSubview:label];
    self.datelabel = label;
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(view.frame.size.width - 50 - 30, 7, 30, 30)];
    [rightBtn setImage:[UIImage imageNamed:@"icon_next"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightClick) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:rightBtn];
}

-(void)leftClick
{
    self.isOutlay = false;
    self.month --;
    if (self.month < 1) {
        self.year --;
        self.month = 12;
    }
    self.datelabel.text = [NSString stringWithFormat:@"%ld-%02ld",self.year,self.month];
    self.tableArr = [self loadTableViewData:self.datelabel.text];
    [self.tableView reloadData];
    [self reloadPieChartViewData];
}

-(void) rightClick
{
    self.isOutlay = false;
    self.month ++;
    if (self.month > 12) {
        self.year ++;
        self.month = 1;
    }
    self.datelabel.text = [NSString stringWithFormat:@"%ld-%02ld",self.year,self.month];
    self.tableArr = [self loadTableViewData:self.datelabel.text];
    [self.tableView reloadData];
    [self reloadPieChartViewData];
}


-(UITableView *)tableView
{
    if (!_tableView) {
        UITableView *tv = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.pieChartView.frame) + 10, KAScreenW, KAScreenH - CGRectGetMaxY(self.pieChartView.frame) - 10  - 49 - 64) style:UITableViewStylePlain];
        tv.delegate = self;
        tv.dataSource = self;
        tv.bounces = NO;
        tv.separatorInset = UIEdgeInsetsMake(2, 2, 2, 2);
        tv.separatorStyle = UITableViewCellSeparatorStyleNone;
        [tv registerNib:[UINib nibWithNibName:NSStringFromClass([KAMonthTableViewCell class]) bundle:nil] forCellReuseIdentifier:ID];
        tv.tableFooterView = [UIView new];
        _tableView = tv;
    }
    return _tableView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (!self.isOutlay) {
        return [self.tableArr[0] count];
    } else {
        return [self.tableArr[1] count];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KAMonthTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[KAMonthTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    if (!self.isOutlay) {
        cell.monthDict = self.tableArr[0][indexPath.row];
    } else {
        cell.monthDict = self.tableArr[1][indexPath.row];
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    KAMonthTableHeaderView *headerView = [[KAMonthTableHeaderView alloc]initWithFrame:CGRectMake(0, 0, KAScreenW, 21)];
    return headerView;
}

@end
